// file:src/kernel/fs/file.c
// autor:jiangxinpeng
// time:2021.2.23
// copyright:(C) by jiangxinpeng,All right are reserved.

#include <os/file.h>
#include <os/memcache.h>
#include <os/fsal.h>
#include <lib/string.h>
#include <arch/atomic.h>

fsal_file_t *fsal_file_table;

// init system fsal file table
int FsalFileTableInit()
{
    // alloc fsal file table
    fsal_file_table = (fsal_file_t *)KMemAlloc(sizeof(fsal_file_t) * FSAL_FILE_MAX);
    if (fsal_file_table != NULL)
    {
        // init fsal file table
        memset(fsal_file_table, 0, sizeof(fsal_file_t) * FSAL_FILE_MAX);
        return 0;
    }
    return -1;
}

// alloc free fsal file
fsal_file_t *FsalFileAlloc()
{
    fsal_file_t *fsal_file;

    for (int i = 0; i < FSAL_FILE_MAX; i++)
    {
        fsal_file = &fsal_file_table[i];
        if (!fsal_file->flags)
        {
            fsal_file->flags = FSAL_FILE_USING;
            AtomicAdd(&fsal_file->ref, 1);
            return fsal_file;
        }
    }
    return NULL;
}

// free fsal file
int FsalFileFree(fsal_file_t *fsal_file)
{
    if (fsal_file != NULL)
    {
        if (fsal_file->flags != FSAL_FILE_USING)
            return 0;
        // reset flags
        fsal_file->flags = 0;
        AtomicSet(&fsal_file->ref, 0);
        return 0;
    }
    return -1;
}